/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { PureComponent } from "react";
import { Icon, Button } from "antd";
import "./index.less";
import IconFont from "@/components/IconFont";

class LocationBar extends PureComponent {
  constructor() {
    super();
    this.state = {
      loading: null,
    };
    this.listeners = {};
  }

  componentWillUnmount() {
    // 清除定位监听
    for (let key in this.listeners) {
      AMap.event.removeListener(this.listeners[key]);
    }
  }

  componentDidMount() {
    const { __map__: map } = this.props;
    map.plugin(["AMap.Geolocation"], () => {
      this.geolocation = new AMap.Geolocation({
        enableHighAccuracy: true, //是否使用高精度定位，默认:true
        timeout: 5000, //超过5秒后停止定位，默认：无穷大
        maximumAge: 60 * 1000, //定位结果缓存0毫秒，默认：0
        convert: true, //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
      });
      this.startLocation("init");
      this.listeners.complete = AMap.event.addListener(this.geolocation, "complete", e => {
        const { formattedAddress: address, position } = e;
        this.handleLocation({ position, address, action: this.locationAction }, "success");
      }); //返回定位信息
      this.listeners.error = AMap.event.addListener(this.geolocation, "error", () => {
        this.handleLocation(
          { position: { lat: 31.2241, lng: 121.35506 }, address: "", action: this.locationAction },
          "error"
        );
      }); //返回定位出错信息
    });
  }

  startLocation = action => {
    this.locationAction = action;
    this.setState({
      loading: true,
    });
    this.geolocation.getCurrentPosition();
  };

  handleLocation = (data, status) => {
    const { onLocation } = this.props;
    if (onLocation) {
      onLocation(data, status);
    }
    this.setState({
      loading: false,
    });
  };

  render() {
    const { loading } = this.state;
    return (
      <Button
        style={{ color: loading === false ? "#0f89f5" : "" }}
        disabled={loading}
        onClick={this.startLocation.bind(this, "reset")}
        className="map-location-bar"
      >
        {loading ? <Icon type="loading" /> : <IconFont type="location" />}
      </Button>
    );
  }
}

export default LocationBar;
